<template>
  <div>
    <div v-if="fileArr.length || echoFileArr.length" class="upload-list">
      <!-- 回显文件（之前上传并保存的文件） -->
      <!-- <li v-for="fileObj in echoFileArr" :key="fileObj.id" class="list-fileObj">
        <a class="fileObj-a">
          <img :src="fileType(fileObj.name)" />
          <div class="info-box">
            <div class="file-name">
              {{ fileObj.name }}
            </div>
            <div class="file-size">{{ formatFileSize(fileObj.size) }}</div>
          </div>
        </a>
      </li> -->
      <!-- 已选文件 -->
      <div
        v-for="fileObj in fileArr"
        :key="fileObj.id"
        class="arco-upload-list-item"
      >
        <div class="arco-upload-list-item-content">
          <span class="arco-upload-list-item-thumbnail">
            <img :src="fileType(fileObj.name)" />
          </span>
          <div class="arco-upload-list-item-name">
            <div class="arco-upload-list-item-name-text">{{
              fileObj.name
            }}</div>
            <div class="discription">
              <a-input
                v-model="fileObj.description"
                placeholder="请输入描述"
                size="mini"
              />
              <icon-pen class="icon" />
            </div>
            <div v-if="percentage[getKey(fileObj)] > 1" class="percentage">
              <a-progress
                :percent="(percentage[getKey(fileObj)] || 0) / 100"
                :stroke-width="2"
                :color="proColor"
                :show-text="false"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { Message } from '@arco-design/web-vue';
  import pngIcon from '@/assets/images/file-manager/png.png';
  import jpgIcon from '@/assets/images/file-manager/jpg.png';
  import docIcon from '@/assets/images/file-manager/doc.png';
  import xlsIcon from '@/assets/images/file-manager/xls.png';
  import rvtIcon from '@/assets/images/file-manager/rvt.png';
  import otherIcon from '@/assets/images/file-manager/other.png';
  import { deleteFile } from '../api';

  const props = defineProps({
    // 已选文件数组
    fileArr: {
      type: Array,
      default() {
        return [];
      },
    },
    // 回显文件数组(之前已经保存过的文件)
    echoFileArr: {
      type: Array,
      default() {
        return [];
      },
    },
    // 文件的实时上传进度
    percentage: {
      type: Object,
      default() {
        return {};
      },
    },
    // 进度条颜色
    proColor: {
      type: String,
      default: 'rgb(22, 93, 255)',
    },
  });

  // 文件类型对应图标对象
  const fileTypeIcon = {
    jpg: jpgIcon,
    jpeg: jpgIcon,
    png: pngIcon,
    // gif: 'doc_img',
    // bmp: 'doc_img',
    // txt: 'doc_txt',
    // css: 'doc_code',
    // html: 'doc_html',
    xls: xlsIcon,
    xlsx: xlsIcon,
    // exe: 'doc_exe',
    // iso: 'doc_iso',
    // ppt: 'doc_ppt',
    // pptx: 'doc_ppt',
    // zip: 'doc_zip',
    // rar: 'doc_zip',
    // pdf: 'doc_pdf',
    doc: docIcon,
    docx: docIcon,
    rvt: rvtIcon,
    // dir: 'doc_folder',
  };

  // 格式化文件大小
  const formatFileSize = (value) => {
    if (value === null || value === '' || value === '0') {
      return '-';
    }
    const unitArr = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    let index = 0;
    const srcsize = parseFloat(value);
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    const size = srcsize / 1024 ** index;
    const sizeStr = size.toFixed(2); // 保留的小数位数
    return sizeStr + unitArr[index];
  };

  // 根据文件类型确定图标样式
  const fileType = (filename: string) => {
    const fileA = filename.split('.');
    let type = otherIcon;
    Object.keys(fileTypeIcon).forEach((key) => {
      if (key === fileA[fileA.length - 1].toLowerCase()) {
        type = fileTypeIcon[key];
      }
    });
    return type;
  };
  // eslint-disable-next-line no-undef
  const getKey = (fileObj: WebUploader.File) => {
    return `${fileObj.name}&${fileObj.lastModifiedDate}`;
  };
  // 取消分片上传/删除已上传文件
  const close = (fileObj, index) => {
    const key = getKey(fileObj);

    if (props.percentage[key] < 100) {
      // TODO
      // this.$emit('cancelFile', fileObj); // 分片上传取消
    } else {
      const data = {
        f8s: new Array(fileObj.fileToken),
      };

      deleteFile(data)
        .then((res) => {
          if (res.status) {
            // eslint-disable-next-line vue/no-mutating-props
            props.fileArr.splice(index, 1);
            // TODO
            // this.$emit('update:fileArr', this.fileArr);

            // eslint-disable-next-line vue/no-mutating-props
            delete props.percentage[key];
            // TODO
            // this.$emit('update:percentage', percentage);
          }
        })
        .catch((err) => {
          Message.error(`文件删除失败：${err}`);
        });
    }
  };
  // 删除回显的文件
  const deleteEchoFile = (fileObj, index) => {
    const data = {
      f8s: new Array(fileObj.fileToken),
    };

    deleteFile(data)
      .then((res) => {
        if (res.status) {
          // eslint-disable-next-line vue/no-mutating-props
          props.echoFileArr.splice(index, 1);
          // TODO
          // this.$emit('update:echoFileArr', this.echoFileArr);
        }
      })
      .catch((err) => {
        Message.error(`文件删除失败：${err}`);
      });
  };
</script>

<style lang="less" scoped>
  /* 覆盖文件列表默认样式 */
  .upload-list {
    width: 100%;
    margin-top: 24px;
    max-height: 260px;
    overflow: auto;

    .arco-upload-list-item:first-of-type {
      margin-top: 0;
    }

    .arco-upload-list-item-content {
      border-radius: var(--border-radius-medium);
    }

    img {
      border-radius: 4px;
    }
    .arco-upload-list-item-name {
      position: relative;
      flex-direction: column;
      align-items: flex-start;
      line-height: 18px;
      height: 40px;

      .arco-upload-list-item-name-text {
        cursor: auto;
      }

      .arco-input-wrapper {
        width: 275px;
        padding: 0;
        background-color: var(--color-fill-1);
        border: none;
        color: #4e5969;
        .arco-input-size-mini {
          padding: 0;
          ::-webkit-input-placeholder {
            color: #86909c;
          }
          :-moz-placeholder {
            color: #86909c;
          }
          ::-moz-placeholder {
            color: #86909c;
          }
          :-ms-input-placeholder {
            color: #86909c;
          }
        }
      }

      .arco-input-focus {
        border-color: var(--color-fill-1);
      }
    }
  }

  .discription {
    display: flex;
    align-items: center;

    .icon {
      color: #3366ff;
      font-size: 16px;
    }

    :deep(.arco-input.arco-input-size-mini) {
      height: 16px;
      line-height: 16px;
    }
  }

  .percentage {
    width: 100%;
    line-height: 0;
    // position: relative;
    // left: 0;
    // right: 0;
    // bottom: 0;
  }
</style>
